﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;

public partial class Order_ReturnDocEdit : System.Web.UI.Page
{
    private DataTable TempDataTable
    {
        get
        {
            DataTable tempDataTable = null;
            if (ViewState["TempDataTable"] != null)
            {
                tempDataTable = (DataTable)ViewState["TempDataTable"];
            }
            return tempDataTable;
        }
        set
        {
            ViewState["TempDataTable"] = value;
        }
    }

    private DataSet DstReturnDocDetails
    {
        get
        {
            DataSet dstReturnDocDetails = null;
            if (ViewState["DstReturnDocDetails"] != null)
            {
                dstReturnDocDetails = (DataSet)ViewState["DstReturnDocDetails"];
            }
            return dstReturnDocDetails;
        }
        set
        {
            ViewState["DstReturnDocDetails"] = value;
        }
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        Page.Theme = BLL.Common.GetWSMThemes();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("400102");
        if (!IsPostBack)
        {

            ((Button)BUTTONDJ1.Controls[0]).Visible = false;
            ((Button)BUTTONDJ1.Controls[2]).Visible = false;
            //((Button)BUTTONDJ1.Controls[4]).Visible = false;
            ((Button)BUTTONDJ1.Controls[8]).Enabled = false;
            ((Button)BUTTONDJ1.Controls[10]).Enabled = false;
            ((Button)BUTTONDJ1.Controls[10]).Attributes.Add("onclick", "Mask();");
            ((Button)BUTTONDJ1.Controls[12]).Visible = false;
            //((Button)BUTTONDJ1.Controls[14]).Enabled = false;
            ((Button)BUTTONDJ1.Controls[16]).Enabled = false;
            ((Button)BUTTONDJ1.Controls[18]).Enabled = false;
            if (Request.QueryString["code"] != null)
            {
                GetDefaultData();
                BindOrderNote();
                GetReturnDocInfo(Request.QueryString["code"].ToString().Trim());
                GetReturnDocDetailData(Request.QueryString["code"].ToString().Trim());

                
                BindPayDetail();
            }
            
        }
    }
    private void GetDefaultData()
    {
        List<Model.RETURNTYPE> rtList = new BLL.RETURNTYPE().GetAllList();
        DropDownList2.DataSource = rtList;
        DropDownList2.DataTextField = "RT_NAME";
        DropDownList2.DataValueField = "RT_CODE";
        DropDownList2.DataBind();

        List<Model.USERS> uList = new BLL.USERS().GetList(String.Empty, " users_stop=0 ", " users_default desc ");
        DropDownList3.DataSource = uList;
        DropDownList3.DataTextField = "users_name";
        DropDownList3.DataValueField = "users_code";
        DropDownList3.DataBind();
    }
    private void BindOrderNote()
    {
        DataSet dst = new BLL.RETURNNOTE().GetOrderNoteById(Request.QueryString["code"].ToString().Trim());
        RETURNNOTEListControl1.Bind(dst);
    }
    private void GetReturnDocDetailData(string returndocid)
    {
        this.DstReturnDocDetails = new BLL.RETURNDOCDETAIL().GetModel(returndocid);
        DataList1.DataSource = this.DstReturnDocDetails.Tables[0].DefaultView;
        DataList1.DataBind();

    }
    private void GetReturnDocInfo(string returndocid)
    {
        DataSet ds = new BLL.RETURNDOC().GetModelDataSet(returndocid);
        DataTable dt = ds.Tables[0];
        lbldm.Text = dt.Rows[0]["RD_ID"].ToString();
        lblorder.Text = dt.Rows[0]["RD_DOCID"].ToString();
        lblorder.NavigateUrl = "~/Order/OrderDetail.aspx?code=" + dt.Rows[0]["RD_DOCID"].ToString().Trim();
        lblgmr.Text = dt.Rows[0]["rd_customercode"].ToString();
        lblRealName.Text = dt.Rows[0]["gkmc"].ToString();
        lblNickName.Text = dt.Rows[0]["byzd5"] == null ? "" : dt.Rows[0]["byzd5"].ToString();
        //绑定物流公司
        List<Model.TRANER> traner = new BLL.TRANER().GetAllList();
        ddlwlgs.DataSource = traner;
        ddlwlgs.DataTextField = "TRANER_NAME";
        ddlwlgs.DataValueField = "TRANER_CODE";
        ddlwlgs.DataBind();
        ddlwlgs.SelectedValue = dt.Rows[0]["RD_TRANER"].ToString();
        txtwlfy.Text = Decimal.Round((Decimal)dt.Rows[0]["RD_TRANCOST"], 2).ToString();
        txtthr.Text = dt.Rows[0]["RD_RETURNER"].ToString();
        Label14.Text = Decimal.Round((Decimal)dt.Rows[0]["RD_TRANCOST"], 2).ToString();
        txtthrdh.Text = dt.Rows[0]["RD_RETURNPHONE1"].ToString();
        txtthrsj.Text = dt.Rows[0]["RD_RETURNERPHONE2"].ToString();
        Label7.Text = dt.Rows[0]["RD_TRANID"].ToString();
        Model.USERS user = new BLL.USERS().GetModel(dt.Rows[0]["RD_CREATER"].ToString());
        if (user != null)
        {
            lbCreator.Text = user.USERS_NAME;
        }
        else
        {
            lbCreator.Text = "不存在";
        }
        txtthryb.Text = dt.Rows[0]["RD_RETURNPOSTCODE"].ToString();
        Label9.Text = dt.Rows[0]["RD_NOTE"].ToString();
        txtthrdz.Text = dt.Rows[0]["RD_RETURNADDRESS"].ToString();

        //ddlfyxz.SelectedValue = dt.Rows[0]["RD_COSTTYPE"].ToString().Trim();
        //Label12.Text = dt.Rows[0]["RD_RETURNTYPE"].ToString().Trim() == "000" ? "结余款" : "其  他";
        hidReturnDocAmt.Value = String.Format("{0:0.00}", dt.Rows[0]["RD_AMT"]);
        Label13.Text = String.Format("{0:0.00}",dt.Rows[0]["RD_AAMT"]);
        Label14.Text = String.Format("{0:0}",dt.Rows[0]["RD_SUBITG"]);
        CheckBox1.Checked = dt.Rows[0]["RD_CHECK"].ToString() == "1" ? true : false;
        CheckBox2.Checked = dt.Rows[0]["RD_CLEAR"].ToString() == "1" ? true : false;
        CheckBox3.Checked = dt.Rows[0]["RD_DELETE"].ToString() == "1" ? true : false;
        Label15.Text = Decimal.Round((Decimal)dt.Rows[0]["RD_CLEAREDAMT"], 2).ToString();
        txtRangLi.Text = string.Format("{0:0.00}", dt.Rows[0]["RD_OFFERAMT"]);
        lblProductAmt.Text = string.Format("{0:0.00}", dt.Rows[0]["RD_AAMT"]);
        lblCreateDate.Text = dt.Rows[0]["RD_CREATEDATE"].ToString();
        lblOldWLFY.Text = dt.Rows[0]["ORDER_TRANCOST"].ToString();
        lblCheckDate.Text = dt.Rows[0]["RD_CHECKDATE"].ToString();
        lblACheckDate.Text = dt.Rows[0]["RD_ORDER_ACHECKDATE"].ToString();
        lblChecker.Text = dt.Rows[0]["RD_CHECKER"].ToString();
        lblAChecker.Text = dt.Rows[0]["RD_ACHECKER"].ToString();

        if (CheckBox1.Checked || CheckBox3.Checked)
        {
            ((Button)BUTTONDJ1.Controls[14]).Enabled = false;
            ((Button)BUTTONDJ1.Controls[6]).Enabled = false;
            ((Button)BUTTONDJ1.Controls[4]).Visible = false;
            ((Button)BUTTONDJ1.Controls[8]).Enabled = true;
            ((Button)BUTTONDJ1.Controls[10]).Enabled = true;
            pnlReturnDocInfo.Enabled = false;
        }
        //btnClear.Visible = dt.Rows[0]["RD_SECDEAL"].ToString() == "1" ? true : false;
        btnClear.Enabled = dt.Rows[0]["RD_CHECK"].ToString() == "1" ? true : false;
        if (dt.Rows[0]["RD_CHECK"].ToString() == "1")
        {
            btnClear.Enabled = dt.Rows[0]["RD_CLEAR"].ToString() == "1" ? false : true;
        }
        DropDownList2.SelectedValue = dt.Rows[0]["RD_REASON"].ToString();
        DropDownList3.SelectedValue = dt.Rows[0]["RD_DUTY"].ToString();
        CheckBox4.Checked = dt.Rows[0]["RD_ACHECK"].ToString() == "1" ? true : false;
        if (CheckBox4.Checked)
        {
            ((Button)BUTTONDJ1.Controls[8]).Enabled = false;
            ((Button)BUTTONDJ1.Controls[10]).Enabled = false;
            DataList1.Enabled = false;
            pnlReturnDocInfo.Enabled = false;
        }
        if (CheckBox3.Checked)
        {
            ((Button)BUTTONDJ1.Controls[8]).Enabled = false;
            ((Button)BUTTONDJ1.Controls[10]).Enabled = false;
            DataList1.Enabled = false;
        }
        if (CheckBox1.Checked)
        {
            DataList1.Enabled = false;
        }
        if (CheckBox2.Checked)
        {
            DataList1.Enabled = false;
        }
    }
    private void BindPayDetail()
    {
        this.TempDataTable = (new BLL.RETURNDOCPAYDETAIL().GetDetailsById(Request.QueryString["code"].ToString())).Tables[0];
        dlistPayDocPayDetail.DataSource = this.TempDataTable;
        dlistPayDocPayDetail.DataBind();
    }

    #region 作废
    public void Delete()
    {
        if (!Check.CheckPermission("400102", "00018"))
        {
            Share.Alert(Page, "无权操作"); return;
        }
        Model.RETURNDOC od = new BLL.RETURNDOC().GetModel(Request.QueryString["code"].ToString());
        if (od.RD_CHECK == 1)
        {
            Share.Alert(this.Page, "已核准的退货单不能作废！"); return;
        }
        od.RD_DELETE = 1;
        od.RD_DELETER = Share.UserValue(0);
        od.RD_DELETEDATE = DateTime.Now;
        od.RD_REASON = DropDownList2.SelectedValue;
        if (Label9.Text.Trim() == "")
        {
            Share.Alert(this.Page, "请在备注中填写作废原因！"); return;
        }
        od.RD_NOTE = Label9.Text.Trim();
        if (new BLL.RETURNDOC().Update(od))
        {
            Share.InsertLog("400102", "00018");
            Response.Redirect("ReturnDocEdit.aspx?code=" + Request.QueryString["code"].ToString());
        }
        else
        {
            Share.Alert(Page, "操作失败"); return;
        }
    }
    #endregion
    #region 保存事件
    public void Save()
    {
        if (!Check.CheckPermission("400102", "00017"))
        {
            Share.Alert(Page, "无权操作"); return;
        }
        try
        {
            List<Model.RETURNDOC> list = new List<Model.RETURNDOC>();

            Model.RETURNDOC returndoc = new BLL.RETURNDOC().GetModel(Request.QueryString["code"].ToString().Trim());
            if (returndoc != null)
            {
                if (returndoc.RD_CHECK == 1)
                {
                    Share.Alert(Page, "退货单已审核,不允许修改！"); return;
                }
            }
            returndoc.RD_ID = this.lbldm.Text.Trim();
            returndoc.RD_CUSTOMERCODE = this.lblgmr.Text.Trim();
            returndoc.RD_DOCID = this.lblorder.Text.Trim();
            returndoc.RD_TRANER = this.ddlwlgs.SelectedValue.ToString();
            returndoc.RD_TRANCOST = txtwlfy.Text.Trim() == "" ? 0.00M : Convert.ToDecimal(txtwlfy.Text.Trim());

            //returndoc.RD_COSTTYPE = ddlfyxz.SelectedValue;
            returndoc.RD_TRANID = this.Label7.Text.ToString();
            returndoc.RD_RETURNER = this.txtthr.Text.ToString();
            returndoc.RD_RETURNPHONE1 = this.txtthrdh.Text.Trim().ToString();
            returndoc.RD_RETURNERPHONE2 = this.txtthrsj.Text.Trim().ToString();
            returndoc.RD_RETURNADDRESS = this.txtthrdz.Text.Trim().ToString();
            returndoc.RD_RETURNPOSTCODE = this.txtthryb.Text.ToString();
            returndoc.RD_NOTE = this.Label9.Text.Trim();
            returndoc.RD_CLEAREDAMT = Convert.ToDecimal(this.Label15.Text.Trim());
            returndoc.RD_SUBITG = Convert.ToDecimal(this.Label14.Text.Trim());
            //returndoc.RD_RETURNTYPE = this.Label12.Text.Trim();
            
            returndoc.RD_AAMT = returndoc.RD_AMT - Convert.ToDecimal(txtwlfy.Text) + Convert.ToDecimal(txtRangLi.Text);
            returndoc.RD_REASON = DropDownList2.SelectedValue;
            returndoc.RD_DUTY = DropDownList3.SelectedValue;
            returndoc.RD_OFFERAMT = Convert.ToDecimal(txtRangLi.Text);
            list.Add(returndoc);
            new BLL.RETURNDOC().Update(list);

            HtmlInputHidden hidDetailId;
            DropDownList dropKW;
            StringBuilder strSql = new StringBuilder();
            for (int i = 0; i < DataList1.Items.Count; i++)
            {
                hidDetailId = (HtmlInputHidden)DataList1.Items[i].FindControl("hidDetailId");
                dropKW = (DropDownList)DataList1.Items[i].FindControl("dropKW");

                strSql.Append("update RETURNDOCDETAIL set RDD_FIELD2='");
                strSql.Append(dropKW.SelectedValue);
                strSql.Append("' where RDD_ID='");
                strSql.Append(Request.QueryString["code"].ToString());
                strSql.Append("' and RDD_DETAILID='");
                strSql.Append(hidDetailId.Value);
                strSql.Append("'|");

            }
            string stringSql = strSql.ToString();
            char[] charToTrim = new char[] { '|' };
            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
            new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);

            Response.Redirect("ReturnDocEdit.aspx?code=" + Request.QueryString["code"].ToString().Trim());
        }
        catch (FormatException ex)
        {
            Share.Alert(Page, "您输入的数值有误，请输入正确的数值！");
        }
        catch (Exception ex)
        {
            Share.Alert(Page, ex.Message);
        }
        
    }
    #endregion
    #region 保存方法
    public void SaveMethod()
    {
        if (!Check.CheckPermission("400102", "00017"))
        {
            Share.Alert(Page, "无权操作"); return;
        }
       // try
        //{
            List<Model.RETURNDOC> list = new List<Model.RETURNDOC>();

            Model.RETURNDOC returndoc = new BLL.RETURNDOC().GetModel(Request.QueryString["code"].ToString().Trim());
            if (returndoc != null)
            {
                if (returndoc.RD_CHECK == 1)
                {
                    Share.Alert(Page, "退货单已审核,不允许修改！"); return;
                }
            }
            //returndoc.RD_ID = this.lbldm.Text.Trim();
            //returndoc.RD_CUSTOMERCODE = this.lblgmr.Text.Trim();
            //returndoc.RD_DOCID = this.lblorder.Text.Trim();
            returndoc.RD_TRANER = this.ddlwlgs.SelectedValue.ToString();
            returndoc.RD_TRANCOST = txtwlfy.Text.Trim() == "" ? 0.00M : Convert.ToDecimal(txtwlfy.Text.Trim());

            //returndoc.RD_COSTTYPE = ddlfyxz.SelectedValue;
            returndoc.RD_TRANID = this.Label7.Text.ToString();
            //returndoc.RD_RETURNER = this.txtthr.Text.ToString();
            //returndoc.RD_RETURNPHONE1 = this.txtthrdh.Text.Trim().ToString();
            //returndoc.RD_RETURNERPHONE2 = this.txtthrsj.Text.Trim().ToString();
            //returndoc.RD_RETURNADDRESS = this.txtthrdz.Text.Trim().ToString();
            //returndoc.RD_RETURNPOSTCODE = this.txtthryb.Text.ToString();
            returndoc.RD_NOTE = this.Label9.Text.Trim();
            //returndoc.RD_CLEAREDAMT = Convert.ToDecimal(this.Label15.Text.Trim());
            //returndoc.RD_SUBITG = Convert.ToDecimal(this.Label14.Text.Trim());
            //returndoc.RD_RETURNTYPE = this.Label12.Text.Trim();
            //returndoc.RD_AAMT = returndoc.RD_AMT - Convert.ToDecimal(txtwlfy.Text) + Convert.ToDecimal(txtRangLi.Text);
            returndoc.RD_REASON = DropDownList2.SelectedValue;
            returndoc.RD_DUTY = DropDownList3.SelectedValue;
            //returndoc.RD_OFFERAMT = Convert.ToDecimal(txtRangLi.Text);
            list.Add(returndoc);
            new BLL.RETURNDOC().Update(list);
/*
            HtmlInputHidden hidDetailId;
            DropDownList dropKW;
            StringBuilder strSql = new StringBuilder();
            for (int i = 0; i < DataList1.Items.Count; i++)
            {
                hidDetailId = (HtmlInputHidden)DataList1.Items[i].FindControl("hidDetailId");
                dropKW = (DropDownList)DataList1.Items[i].FindControl("dropKW");

                strSql.Append("update RETURNDOCDETAIL set RDD_FIELD2='");
                strSql.Append(dropKW.SelectedValue);
                strSql.Append("' where RDD_ID='");
                strSql.Append(Request.QueryString["code"].ToString());
                strSql.Append("' and RDD_DETAILID='");
                strSql.Append(hidDetailId.Value);
                strSql.Append("'|");

            }
            string stringSql = strSql.ToString();
            char[] charToTrim = new char[] { '|' };
            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
            new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);
        */
        //}
        //catch (FormatException ex)
        //{
        //    Share.Alert(Page, "您输入的数值有误，请输入正确的数值！");
        //}
        //catch (Exception ex)
        //{
        //    Share.Alert(Page, ex.Message);
        //}

    }
    #endregion
    #region 审批
    public void Audit()
    {
        //try
        //{
        if (!Check.CheckPermission("400102", "00010"))
        {
            Share.Alert(Page, "无权操作"); return;
        }

        Model.RETURNDOC returndoc = new BLL.RETURNDOC().GetModel(Request.QueryString["code"].ToString().Trim());
        if (returndoc != null)
        {
            if (returndoc.RD_CHECK == 1)
            {
                Share.Alert(Page, "退货单已审核,不允许重复操作！"); return;
            }
        }
        SaveMethod();
        string cpkwdm = ConfigurationManager.AppSettings["cpkwdm"] == "" ? "001" : ConfigurationManager.AppSettings["cpkwdm"];
        if (new BLL.RETURNDOCDETAIL().P_ReturnOrder_Audit(System.Configuration.ConfigurationSettings.AppSettings["ckdm"].ToString(), System.Configuration.ConfigurationSettings.AppSettings["kwdm"].ToString(), cpkwdm, Request.QueryString["code"].ToString().Trim(), Share.UserValue(0), Label7.Text.Trim()))
        {
            Share.InsertLog("400102", "00010");

            Response.Redirect("ReturnDocEdit.aspx?code=" + Request.QueryString["code"].ToString());
        }
        else
        {
            Share.Alert(Page, "审批失败"); return;
        }
        //}
        //catch (FormatException ex)
        //{
        //    Share.Alert(Page, "您输入的数值有误，请输入正确的数值！");
        //}
        //catch (Exception ex)
        //{
        //    Share.Alert(Page, ex.Message);
        //}
    }
    #endregion
    #region 反审批


    public void UnAudit()
    {
        if (!Check.CheckPermission("400102", "00011"))
        {
            Share.Alert(Page, "无权操作"); return;
        }
        Model.RETURNDOC returnDoc = new BLL.RETURNDOC().GetModel(Request.QueryString["code"].ToString().Trim());
        if (returnDoc == null)
        {
            Share.Alert(this.Page, "系统无法找到退货单信息！"); return; 
        }
        DataSet ds = new BLL.RETURNDOCDETAIL().GetModel(Request.QueryString["code"].ToString().Trim());
        if (ds.Tables[0].Rows.Count == 0)
        {
            Share.Alert(this.Page, "系统无法找到该退货单的退货明细！"); return; 
        }

        if (returnDoc != null)
        {
            if (returnDoc.RD_CHECK == 0)
            {
                Share.Alert(Page, "退货单未被审核,不允许反审核！"); return;
            }
        }
        StringBuilder strSql = new StringBuilder();
        strSql.Append("update RETURNDOC set RD_CHECK=0 where RD_ID='");
        strSql.Append(Request.QueryString["code"].ToString().Trim());
        strSql.Append("'|");

        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            if (ds.Tables[0].Rows[i]["RDD_FIELD2"].ToString() == ConfigurationManager.AppSettings["kwdm"].ToString())
            {
                strSql.Append("update spkcb set sl3=sl3-");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_QTY"].ToString());
                strSql.Append(",sl=sl-");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_QTY"].ToString());
                strSql.Append(" where ckdm='");
                strSql.Append(ConfigurationManager.AppSettings["ckdm"].ToString());
                strSql.Append("' and kwdm='");
                strSql.Append(ConfigurationManager.AppSettings["kwdm"].ToString());
                strSql.Append("' and spdm='");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_CMDCODE"].ToString());
                strSql.Append("' and gg1dm='");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_COLORCODE"].ToString());
                strSql.Append("' and gg2dm='");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_SIZECODE"].ToString());
                strSql.Append("'|");
            }
            else if (ds.Tables[0].Rows[i]["RDD_FIELD2"].ToString() == ConfigurationManager.AppSettings["cpkwdm"].ToString())
            {
                strSql.Append("update spkcb set sl3=sl3-");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_QTY"].ToString());
                strSql.Append(",sl=sl-");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_QTY"].ToString());
                strSql.Append(" where ckdm='");
                strSql.Append(ConfigurationManager.AppSettings["ckdm"].ToString());
                strSql.Append("' and kwdm='");
                strSql.Append(ConfigurationManager.AppSettings["cpkwdm"].ToString());
                strSql.Append("' and spdm='");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_CMDCODE"].ToString());
                strSql.Append("' and gg1dm='");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_COLORCODE"].ToString());
                strSql.Append("' and gg2dm='");
                strSql.Append(ds.Tables[0].Rows[i]["RDD_SIZECODE"].ToString());
                strSql.Append("'|");
            }
        }

        string stringSql = strSql.ToString();
        char[] charToTrim = new char[] { '|' };
        string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
        if (new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray))
        {
            Share.InsertLog("400102", "00011");
            Response.Redirect("ReturnDocEdit.aspx?code=" + Request.QueryString["code"].ToString());
        }
        else
        {
            Share.Alert(Page, "反审批失败"); return;
        }
    }
    #endregion
    #region 财务审核
    public void CAudit()
    {
        if (!Check.CheckPermission("400102", "00012"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
            StringBuilder strSqlToUpdateErpDB = new StringBuilder();
            string operatorId = Share.UserValue(0);
            Model.RETURNDOC returnDoc = new BLL.RETURNDOC().GetModel(Request.QueryString["code"].ToString());
            if (returnDoc == null)
            {
                Share.Alert(this.Page, "系统无法查询到此退货单信息！"); return;
            }

            Model.ORDERDOC orderDoc = new BLL.ORDERDOC().GetModel(returnDoc.RD_DOCID);
            if (orderDoc == null)
            {
                Share.Alert(this.Page, "系统无法查询到此退货单关联的订单信息！"); return;
            }

            Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(orderDoc.ORDER_CUSTOMERCODE);
            if (userInfo == null)
            {
                throw new Exception("系统内无此会员信息！");
            }
            Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

            if (userAccount == null)
            {
                strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                strSqlToUpdateBStyleDB.Append(userInfo.DM);
                strSqlToUpdateBStyleDB.Append("',0)|");

                strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                strSqlToUpdateErpDB.Append(userInfo.DM);
                strSqlToUpdateErpDB.Append("',0)|");
            }

            string key = ConfigurationManager.AppSettings["CODE"];
            string ret = "";

            #region 不含担保交易
            if (orderDoc.ORDER_SECDEAL == 0)
            {
                decimal totalPayAmount = 0.00M;
                decimal accountPayAmount = 0.00M;
                for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                {
                    if (this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString() == "003")
                    {
                        accountPayAmount += Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]);
                    }
                    totalPayAmount += Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]);
                }

                if (totalPayAmount >= returnDoc.RD_AAMT)
                {
                    strSqlToUpdateBStyleDB.Append("update returndoc set RD_ACHECK=1,RD_ACHECKER='");
                    strSqlToUpdateBStyleDB.Append(operatorId);
                    strSqlToUpdateBStyleDB.Append("',RD_ORDER_ACHECKDATE='");
                    strSqlToUpdateBStyleDB.Append(DateTime.Now);
                    strSqlToUpdateBStyleDB.Append("',RD_CLEAR=1,RD_CLEAREDAMT=");
                    strSqlToUpdateBStyleDB.Append(totalPayAmount);
                    strSqlToUpdateBStyleDB.Append(" where RD_ID='");
                    strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString());
                    strSqlToUpdateBStyleDB.Append("'|");
                }
                else
                {
                    Share.Alert(this.Page, "退款金额小于退货单实际金额，因此无法执行财务审核！"); return;
                }


                //strSqlToUpdateBStyleDB.Append("update returndoc set RD_ACHECK=1,RD_ACHECKER='");
                //strSqlToUpdateBStyleDB.Append(operatorId);
                //strSqlToUpdateBStyleDB.Append("',RD_ORDER_ACHECKDATE='");
                //strSqlToUpdateBStyleDB.Append(DateTime.Now);
                //strSqlToUpdateBStyleDB.Append("' where RD_ID='");
                //strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString());
                //strSqlToUpdateBStyleDB.Append("'|");

                //构造更新当前用户积分sql
                string strUpdateVipSetSqlString = new BLL.V_VIPSET().BuildUpdateVipSetSqlString(0, 0, returnDoc.RD_SUBITG, orderDoc.ORDER_CUSTOMERCODE);
                strSqlToUpdateBStyleDB.Append(strUpdateVipSetSqlString);
                strSqlToUpdateErpDB.Append(strUpdateVipSetSqlString);

                //构造更新分摊用户积分sql
                StringBuilder[] str = ReturnInergalSql(orderDoc.ORDER_CUSTOMERCODE, returnDoc.RD_SUBITG, returnDoc);

                if (str != null)
                {
                    strSqlToUpdateBStyleDB.Append(str[0].ToString());//更新shop中的积分sql语句

                    strSqlToUpdateErpDB.Append(str[1].ToString());//更新erp中的积分sql语句
                }

                if (accountPayAmount != 0)
                {//构造更新当前用户结余款，可用余额SQL

                    string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount, userInfo.DM);
                    strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                    strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                    string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("006", orderDoc.ORDER_ID, operatorId, operatorId, orderDoc.ORDER_CUSTOMERCODE, accountPayAmount);
                    strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);

                }

                //构造更新分摊用户结余款，可用余额SQL
                StringBuilder[] sql = ReturnCashSql(userInfo.DM, totalPayAmount, returnDoc, operatorId);
                if (sql != null)
                {
                    strSqlToUpdateBStyleDB.Append(sql[0].ToString());

                    strSqlToUpdateErpDB.Append(sql[1].ToString());
                }
                string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                char[] charToTrim = new char[] { '|' };
                string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                if (webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2))
                {
                    Share.InsertLog("400102", "00012");
                    Response.Redirect("returndocedit.aspx?code=" + Request.QueryString["code"].ToString());
                }
                else
                {
                    Share.Alert(this.Page, "财务审核失败，请重新操作！"); return;
                }
            }
            #endregion
            #region 含担保交易


            else
            {
                if (orderDoc.ORDER_CLEAR == 0)
                {
                    DataSet dstNotGetPayDetail = new BLL.PAYDETAIL().GetNotGetPayDetailByOrderId(orderDoc.ORDER_ID);
                    decimal totalPayAmount = 0.00M;
                    decimal accountPayAmount = 0.00M;
                    int count = 0;

                    for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                    {
                        if (this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString() == "003")
                        {
                            accountPayAmount += Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]);
                        }
                        else if (this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString() == "002")
                        {

                            for (int j = 0; j < dstNotGetPayDetail.Tables[0].Rows.Count; j++)
                            {
                                if (dstNotGetPayDetail.Tables[0].Rows[j]["PD_DETAILID"].ToString() == this.TempDataTable.Rows[i]["RDPD_DETAILID"].ToString())
                                {
                                    if (Convert.ToDecimal(dstNotGetPayDetail.Tables[0].Rows[j]["PD_GETAMT"]) + Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]) >= Convert.ToDecimal(dstNotGetPayDetail.Tables[0].Rows[j]["PD_PAYAMT"]))
                                    {
                                        strSqlToUpdateBStyleDB.Append("update paydetail set PD_GET=1,PD_HRAMT=PD_HRAMT+");
                                        strSqlToUpdateBStyleDB.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                                        strSqlToUpdateBStyleDB.Append(" where PD_ID='");
                                        strSqlToUpdateBStyleDB.Append(orderDoc.ORDER_ID);
                                        strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                                        strSqlToUpdateBStyleDB.Append(this.TempDataTable.Rows[i]["RDPD_DETAILID"].ToString());
                                        strSqlToUpdateBStyleDB.Append("'|");
                                        count++;
                                        break;
                                    }
                                    else
                                    {
                                        strSqlToUpdateBStyleDB.Append("update paydetail set PD_HRAMT=PD_HRAMT+");
                                        strSqlToUpdateBStyleDB.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                                        strSqlToUpdateBStyleDB.Append(" where PD_ID='");
                                        strSqlToUpdateBStyleDB.Append(orderDoc.ORDER_ID);
                                        strSqlToUpdateBStyleDB.Append("' and PD_DETAILID='");
                                        strSqlToUpdateBStyleDB.Append(this.TempDataTable.Rows[i]["RDPD_DETAILID"].ToString());
                                        strSqlToUpdateBStyleDB.Append("'|");
                                        break;
                                    }
                                }
                            }

                        }
                        totalPayAmount += Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]);
                    }

                    if (count == dstNotGetPayDetail.Tables[0].Rows.Count)
                    {
                        strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_CLEAR=1,ORDER_CLEARAMT=ORDER_CLEARAMT+");
                        strSqlToUpdateBStyleDB.Append(totalPayAmount);
                        strSqlToUpdateBStyleDB.Append(",BYZD9='"); //结算时间
                        strSqlToUpdateBStyleDB.Append(DateTime.Now);
                        strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                        strSqlToUpdateBStyleDB.Append(orderDoc.ORDER_ID);
                        strSqlToUpdateBStyleDB.Append("'|");
                    }
                    else
                    {
                        strSqlToUpdateBStyleDB.Append("update orderdoc set ORDER_CLEARAMT=ORDER_CLEARAMT+");
                        strSqlToUpdateBStyleDB.Append(totalPayAmount);
                        strSqlToUpdateBStyleDB.Append(" where ORDER_ID='");
                        strSqlToUpdateBStyleDB.Append(orderDoc.ORDER_ID);
                        strSqlToUpdateBStyleDB.Append("'|");
                    }

                    if (totalPayAmount >= returnDoc.RD_AAMT)
                    {
                        strSqlToUpdateBStyleDB.Append("update returndoc set RD_ACHECK=1,RD_ACHECKER='");
                        strSqlToUpdateBStyleDB.Append(operatorId);
                        strSqlToUpdateBStyleDB.Append("',RD_ORDER_ACHECKDATE='");
                        strSqlToUpdateBStyleDB.Append(DateTime.Now);
                        strSqlToUpdateBStyleDB.Append("',RD_CLEAR=1,RD_CLEAREDAMT=");
                        strSqlToUpdateBStyleDB.Append(totalPayAmount);
                        strSqlToUpdateBStyleDB.Append(" where RD_ID='");
                        strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString());
                        strSqlToUpdateBStyleDB.Append("'|");
                    }
                    else
                    {
                        Share.Alert(this.Page, "退款金额小于退货单实际金额，因此无法执行财务审核！"); return;
                    }


                    //strSqlToUpdateBStyleDB.Append("update returndoc set RD_ACHECK=1,RD_ACHECKER='");
                    //strSqlToUpdateBStyleDB.Append(operatorId);
                    //strSqlToUpdateBStyleDB.Append("',RD_ORDER_ACHECKDATE='");
                    //strSqlToUpdateBStyleDB.Append(DateTime.Now);
                    //strSqlToUpdateBStyleDB.Append("' where RD_ID='");
                    //strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString());
                    //strSqlToUpdateBStyleDB.Append("'|");

                    string strUpdateVipSetSqlString = new BLL.V_VIPSET().BuildUpdateVipSetSqlString(0, 0, returnDoc.RD_SUBITG, orderDoc.ORDER_CUSTOMERCODE);
                    strSqlToUpdateBStyleDB.Append(strUpdateVipSetSqlString);
                    strSqlToUpdateErpDB.Append(strUpdateVipSetSqlString);

                    //构造更新分摊用户积分sql
                    StringBuilder[] str = ReturnInergalSql(orderDoc.ORDER_CUSTOMERCODE, returnDoc.RD_SUBITG, returnDoc);

                    if (str != null)
                    {
                        strSqlToUpdateBStyleDB.Append(str[0].ToString());//更新shop中的积分sql语句

                        strSqlToUpdateErpDB.Append(str[1].ToString());//更新erp中的积分sql语句
                    }

                    if (accountPayAmount > 0)
                    {   //当前用户
                        string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount, userInfo.DM);
                        strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                        strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                        string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("006", orderDoc.ORDER_ID, operatorId, operatorId, orderDoc.ORDER_CUSTOMERCODE, accountPayAmount);
                        strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);
                    }

                    //构造更新分摊用户结余款，可用余额SQL
                    StringBuilder[] sql = ReturnCashSql(userInfo.DM, totalPayAmount, returnDoc, operatorId);
                    if (sql != null)
                    {
                        strSqlToUpdateBStyleDB.Append(sql[0].ToString());

                        strSqlToUpdateErpDB.Append(sql[1].ToString());
                    }
                    string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                    string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                    char[] charToTrim = new char[] { '|' };
                    string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                    string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                    LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                    if (webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2))
                    {
                        Share.InsertLog("400102", "00012");
                        Response.Redirect("returndocedit.aspx?code=" + Request.QueryString["code"].ToString());
                    }
                    else
                    {
                        Share.Alert(this.Page, "财务审核失败，请重新操作！"); return;
                    }
                }
                else
                {
                    decimal totalPayAmount = 0.00M;
                    decimal accountPayAmount = 0.00M;
                    for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                    {
                        if (this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString() == "003")
                        {
                            accountPayAmount += Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]);
                        }
                        totalPayAmount += Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]);
                    }

                    if (totalPayAmount >= returnDoc.RD_AAMT)
                    {
                        strSqlToUpdateBStyleDB.Append("update returndoc set RD_ACHECK=1,RD_ACHECKER='");
                        strSqlToUpdateBStyleDB.Append(operatorId);
                        strSqlToUpdateBStyleDB.Append("',RD_ORDER_ACHECKDATE='");
                        strSqlToUpdateBStyleDB.Append(DateTime.Now);
                        strSqlToUpdateBStyleDB.Append("',RD_CLEAR=1,RD_CLEAREDAMT=");
                        strSqlToUpdateBStyleDB.Append(totalPayAmount);
                        strSqlToUpdateBStyleDB.Append(" where RD_ID='");
                        strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString());
                        strSqlToUpdateBStyleDB.Append("'|");
                    }
                    else
                    {
                        Share.Alert(this.Page, "退款金额小于退货单实际金额，因此无法执行财务审核！"); return;
                    }


                    //strSqlToUpdateBStyleDB.Append("update returndoc set RD_ACHECK=1,RD_ACHECKER='");
                    //strSqlToUpdateBStyleDB.Append(operatorId);
                    //strSqlToUpdateBStyleDB.Append("',RD_ORDER_ACHECKDATE='");
                    //strSqlToUpdateBStyleDB.Append(DateTime.Now);
                    //strSqlToUpdateBStyleDB.Append("' where RD_ID='");
                    //strSqlToUpdateBStyleDB.Append(Request.QueryString["code"].ToString());
                    //strSqlToUpdateBStyleDB.Append("'|");

                    string strUpdateVipSetSqlString = new BLL.V_VIPSET().BuildUpdateVipSetSqlString(0, 0, returnDoc.RD_SUBITG, orderDoc.ORDER_CUSTOMERCODE);
                    strSqlToUpdateBStyleDB.Append(strUpdateVipSetSqlString);
                    strSqlToUpdateErpDB.Append(strUpdateVipSetSqlString);

                    //构造更新分摊用户积分sql
                    StringBuilder[] str = ReturnInergalSql(orderDoc.ORDER_CUSTOMERCODE, returnDoc.RD_SUBITG, returnDoc);

                    if (str != null)
                    {
                        strSqlToUpdateBStyleDB.Append(str[0].ToString());//更新shop中的积分sql语句

                        strSqlToUpdateErpDB.Append(str[1].ToString());//更新erp中的积分sql语句
                    }

                    if (accountPayAmount > 0)
                    {//当前用户
                        string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(accountPayAmount, userInfo.DM);
                        strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                        strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                        string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("006", orderDoc.ORDER_ID, operatorId, operatorId, orderDoc.ORDER_CUSTOMERCODE, accountPayAmount);
                        strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);
                        
                    }

                    //构造更新分摊用户结余款，可用余额SQL
                    StringBuilder[] sql = ReturnCashSql(userInfo.DM, totalPayAmount, returnDoc, operatorId);
                    if (sql != null)
                    {
                        strSqlToUpdateBStyleDB.Append(sql[0].ToString());

                        strSqlToUpdateErpDB.Append(sql[1].ToString());
                    }
                    string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                    string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                    char[] charToTrim = new char[] { '|' };
                    string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                    string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                    LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                    if (webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2))
                    {
                        Share.InsertLog("400102", "00012");
                        Response.Redirect("returndocedit.aspx?code=" + Request.QueryString["code"].ToString());
                    }
                    else
                    {
                        Share.Alert(this.Page, "财务审核失败，请重新操作！"); return;
                    }
                }
            }
            #endregion
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }
    #endregion
    #region 意见
    public void YiJian()
    {
        if (!Check.CheckPermission("400102", "00021"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        Response.Redirect("AddSuggestion.aspx?ts=tui&code=" + Request.QueryString["code"].ToString().Trim());
    }
    #endregion
    protected void BUTTONDJ1_Load(object sender, EventArgs e)
    {

    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400102", "00015"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        Response.Redirect("../DeliverGoodsManagement/DistributeSettlementAmount.aspx?returnCode=" + lbldm.Text + "&orderCode=" + lblorder.Text);
    }

    protected void dlistPayDocPayDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DropDownList dropDealType = (DropDownList)e.Item.FindControl("dropDealType");
            for (int i = 0; i < dropDealType.Items.Count; i++)
            {
                if (dropDealType.Items[i].Value == this.TempDataTable.Rows[e.Item.ItemIndex]["RDPD_DTCODE"].ToString())
                {
                    dropDealType.SelectedIndex = i;
                    break;
                }
            }

            DropDownList dropPayType = (DropDownList)e.Item.FindControl("dropPayType");

            if (dropPayType != null)
            {
                if (this.TempDataTable.Rows[e.Item.ItemIndex]["RDPD_DTCODE"].ToString() != "")
                {
                    BindDropPayType(this.TempDataTable.Rows[e.Item.ItemIndex]["RDPD_DTCODE"].ToString(), dropPayType);
                    for (int i = 0; i < dropPayType.Items.Count; i++)
                    {
                        if (dropPayType.Items[i].Value.Contains(this.TempDataTable.Rows[e.Item.ItemIndex]["RDPD_PAYTYPE"].ToString() + "|"))
                        {
                            dropPayType.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else
                {
                    BindDropPayType(dropDealType.Items[0].Value, dropPayType);
                }
            }

            
        }
    }

    private void BindDropPayType(string dealType, DropDownList drop)
    {
        DataSet dst = new BLL.PAYTYPE_DEALTYPE().P_DealType_GetPayTypeByCode(dealType);
        ListItem tempItem;
        drop.Items.Clear();
        for (int i = 0; i < dst.Tables[0].Rows.Count; i++)
        {
            tempItem = new ListItem();
            tempItem.Text = dst.Tables[0].Rows[i]["PT_NAME"].ToString();
            tempItem.Value = dst.Tables[0].Rows[i]["PT_CODE"].ToString() + "|" + dst.Tables[0].Rows[i]["PT_HAVEDEAL"].ToString();
            drop.Items.Add(tempItem);
        }

    }

    protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            DropDownList dropKW = (DropDownList)e.Item.FindControl("dropKW");
            dropKW.Items.Clear();
            if (ConfigurationManager.AppSettings["kwdm"] != null)
            {
                ListItem item = new ListItem();
                item.Text = "正品库位";
                item.Value = ConfigurationManager.AppSettings["kwdm"].ToString();
                dropKW.Items.Add(item);
            }
            if (ConfigurationManager.AppSettings["cpkwdm"] != null)
            {
                ListItem item1 = new ListItem();
                item1.Text = "次品库位";
                item1.Value = ConfigurationManager.AppSettings["cpkwdm"].ToString();
                dropKW.Items.Add(item1);
            }

            for (int i = 0; i < dropKW.Items.Count; i++)
            {
                if (this.DstReturnDocDetails.Tables[0].Rows[e.Item.ItemIndex]["RDD_FIELD2"] == null)
                {
                    if (this.DstReturnDocDetails.Tables[0].Rows[e.Item.ItemIndex]["RDD_FIELD2"].ToString() == "")
                    {
                        break;
                    }
                    break;
                }
                if (dropKW.Items[i].Value == this.DstReturnDocDetails.Tables[0].Rows[e.Item.ItemIndex]["RDD_FIELD2"].ToString())
                {
                    dropKW.SelectedIndex = i;
                    break;
                }
            }
        }
    }

    #region 退货单现金分摊
    protected StringBuilder[] ReturnCashSql(string customerName, decimal accountPayAmount, Model.RETURNDOC returnDoc, string operatorId)
    {
        StringBuilder[] strSql = new StringBuilder[2];
        strSql[0] = new StringBuilder("");
        strSql[1] = new StringBuilder("");
        //customers是通过退货单关联的订单作为参数，从订单现金分成流水帐中查出的有过分成记录的客户集
        ArrayList customers = new ArrayList();
        string selCustomer = "select * from BankRollDayToDayAccount where BDDA_BillID='" + returnDoc.RD_DOCID + "'";
        DataSet ds = null;
        string ret = SQLServerDAL.SqlManager.MySqlHelper.ExecDatasetSql(selCustomer, out ds);
        if (ret == "000000")
        {
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                customers.Add(row["BDDA_USERCODE"].ToString());
            }
        }

        BLL.V_VIP_ACCOUNT vip = new BLL.V_VIP_ACCOUNT();
        BLL.BALANCEADJUST adjust = new BLL.BALANCEADJUST();

        BLL.InergalManage inergalManage = new BLL.InergalManage();
        Model.IntergalTypeSet IntergalTypeSetModel = BLL.IntergalTypeSet.GetSysInterTypeSet();  //取基础设置
        if (IntergalTypeSetModel == null)
        {
            Share.Alert(this.Page, "积分/现金分摊数据未设置"); return strSql;
        }
        else
        {
            if (IntergalTypeSetModel.IntergalSetExtendAttribute6 < 1)
            {
                Share.Alert(this.Page, "未设置分摊级次"); return strSql;
            }
            else
            {
                //获取启用层数的积分分成比例

                BLL.RecommendLevelSet RecommendLevelSetbll = new BLL.RecommendLevelSet();
                List<Model.RecommendLevelSet> lists = null;
                string where = "RecommendManLevel<=" + IntergalTypeSetModel.IntergalSetExtendAttribute6.ToString();
                lists = RecommendLevelSetbll.GetList(null, where, null);
                if (lists == null)
                {
                    Share.Alert(this.Page, "积分/现金分摊数据未设置"); return strSql;
                }
                else
                {
                    if (ds != null)
                    {
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            //使用分割线"|"
                            BLL.V_CUSTOMER_AUTO V_CUSTOMER_AUTObll = new BLL.V_CUSTOMER_AUTO();
                            Model.V_CUSTOMER_AUTO V_CUSTOMER_AUTOModel = V_CUSTOMER_AUTObll.GetModel(customerName);
                            if (V_CUSTOMER_AUTOModel != null)
                            {
                                string[] customerGroup = V_CUSTOMER_AUTOModel.CustomerLevel.Split('|');
                                if (customerGroup.Length > 1)  //只有大于1时才会有上级
                                {
                                    for (int j = 0; j < IntergalTypeSetModel.IntergalSetExtendAttribute6; j++) //循环启用级数
                                    {
                                        Model.RecommendLevelSet rs = inergalManage.GetModel(lists, j + 1);
                                        if (j < customerGroup.Length)
                                        {
                                            int len = customerGroup.Length;
                                            if (len - j - 2 > -1)
                                            {
                                                string upcode = customerGroup[len - j - 2];
                                                if (customers.IndexOf(upcode) > -1)
                                                {//customers是通过退货单关联的订单作为参数，从订单现金分成流水帐中查出的有过分成记录的客户集
                                                    //此处判断是过滤掉没有分成记录的客户，不包含当前用户

                                                    DataRow[] row = ds.Tables[0].Select(string.Format(" BDDA_USERCODE='{0}' and BDDA_BillID='{1}'", upcode, returnDoc.RD_DOCID));
                                                    if (row.Length > 0)
                                                    {
                                                        strSql[0].Append(vip.BuildUpdateVipAccountSqlString(accountPayAmount * rs.RecommendCostSeparate / 100, upcode));
                                                        strSql[0].Append(@"insert into BankRollDayToDayAccount (BDDA_QISHU, BDDA_USERCODE, BDDA_BankRoll, BDDA_ShareDate, BDDA_BillID) 
                                                                        values('" + row[0]["BDDA_QISHU"].ToString() + "','" + upcode + "'," + accountPayAmount * rs.RecommendCostSeparate / 100 + ",'" + DateTime.Now.ToShortDateString() + "','" + returnDoc.RD_ID + "')|");
                                                        strSql[0].Append(adjust.BuildInsertMainSqlString("006", returnDoc.RD_DOCID, operatorId, operatorId, upcode, accountPayAmount * rs.RecommendCostSeparate / 100));
                                                        strSql[1].Append(vip.BuildUpdateVipAccountSqlString(accountPayAmount * rs.RecommendCostSeparate / 100, upcode));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return strSql;
    }
    #endregion
    #region 退货积分分成计算

    public StringBuilder[] ReturnInergalSql(string customerName, decimal InergalAmount, Model.RETURNDOC returnDoc)
    {
        StringBuilder[] strSql = new StringBuilder[2];
        strSql[0] = new StringBuilder("");
        strSql[1] = new StringBuilder("");
        string whereStr = "IntergalName ='" + returnDoc.RD_DOCID + "'";
        List<Model.IntegralWasteBook> WasteBookLists = new BLL.IntegralWasteBook().GetList(null, whereStr, null);//退货单对应的订单作为参数，查出订单关联的积分流水帐记录集


        ArrayList customers = new ArrayList();
        foreach (Model.IntegralWasteBook iwb in WasteBookLists)
        {
            customers.Add(iwb.IntergalExtendAttribute1);//customers是通过退货单关联的订单作为参数，从订单分成流水帐中查出的有过分成记录的客户集
        }

        BLL.InergalManage inergalManage = new BLL.InergalManage();
        //系统积分参数设置
        Model.IntergalTypeSet IntergalTypeSetModel = BLL.IntergalTypeSet.GetSysInterTypeSet();
        if (IntergalTypeSetModel == null)
        {
            Share.Alert(this.Page, "积分/现金分摊数据未设置"); return null;
        }
        else
        {
            if (IntergalTypeSetModel.IntergalSetExtendAttribute6 < 1)
            {
                Share.Alert(this.Page, "未设置分摊级次"); return null;
            }
            else
            {
                Model.V_VIPSET vipset = new Model.V_VIPSET();
                BLL.V_VIPSET bll_vipset = new BLL.V_VIPSET();

                //当前用户积分流水帐记录

                vipset = bll_vipset.GetModel(customerName);//得到当前会员积分信息
                string str = "INSERT INTO IntegralWasteBook(IntergalId,IntergalType ,IntergalRange ,IntergalDateTime,IntergalExtendAttribute1,IntergalExtendAttribute3,IntergalExtendAttribute7,IntergalName) values ('" + Guid.NewGuid().ToString() + "'," + "'" + Convert.ToString((int)BLL.InergalManage.InergalTypeEnum.购物积分) + "'," + InergalAmount + ",'" + DateTime.Now.ToString() + "'" + ",'" + customerName + "','" + BLL.InergalManage.InergalTypeEnum.购物积分.ToString() + "'," + vipset.DQJF.ToString() + ",'" + returnDoc.RD_ID + "' )|";
                strSql[0].Append(str);
                //获取启用层数的积分分成比例


                BLL.RecommendLevelSet RecommendLevelSetbll = new BLL.RecommendLevelSet();

                List<Model.RecommendLevelSet> lists = null;
                string where = "RecommendManLevel<=" + IntergalTypeSetModel.IntergalSetExtendAttribute6.ToString();
                lists = RecommendLevelSetbll.GetList(null, where, null);
                if (lists == null)
                {
                    Share.Alert(this.Page, "积分/现金分摊数据未设置"); return null;
                }
                else
                {
                    //客户积分等级
                    BLL.V_CUSTOMER_AUTO V_CUSTOMER_AUTObll = new BLL.V_CUSTOMER_AUTO();

                    Model.V_CUSTOMER_AUTO V_CUSTOMER_AUTOModel = V_CUSTOMER_AUTObll.GetModel(customerName);

                    string[] customerGroup = V_CUSTOMER_AUTOModel.CustomerLevel.Split('|');

                    if (customerGroup.Length > 1)  //只有大于1时才会有上级
                    {
                        for (int j = 0; j < IntergalTypeSetModel.IntergalSetExtendAttribute6; j++) //循环启用级数
                        {
                            Model.RecommendLevelSet rs = inergalManage.GetModel(lists, j + 1);
                            if (j < customerGroup.Length)
                            {
                                int len = customerGroup.Length;
                                if (len - j - 2 > -1)
                                {
                                    string upcode = customerGroup[len - j - 2];
                                    if (customers.IndexOf(upcode) > -1)
                                    {//customers是通过退货单关联的订单作为参数，从订单积分分成流水帐中查出的有过分成记录的客户集
                                        //此处判断是过滤掉没有分成记录的客户，不包含当前用户

                                        strSql[0].Append(bll_vipset.BuildUpdateVipSetSqlString(0, 0, returnDoc.RD_SUBITG, returnDoc.RD_CUSTOMERCODE));
                                        vipset = bll_vipset.GetModel(upcode);//得到上级会员积分信息
                                        strSql[0].Append("INSERT INTO IntegralWasteBook(IntergalId,IntergalType ,IntergalRange ,IntergalDateTime,IntergalExtendAttribute1,IntergalExtendAttribute3,IntergalExtendAttribute7,IntergalName) values ('" + Guid.NewGuid().ToString() + "'," + "'" + Convert.ToString((int)BLL.InergalManage.InergalTypeEnum.购物积分) + "'," + InergalAmount * rs.RecommendInergalSeparate / 100 + ",'" + DateTime.Now.ToString() + "'" + ",'" + upcode + "','" + BLL.InergalManage.InergalTypeEnum.购物积分.ToString() + "'," + vipset.DQJF.ToString() + ",'" + returnDoc.RD_ID + "' )|");

                                        strSql[1].Append(bll_vipset.BuildUpdateVipSetSqlString(0, 0, returnDoc.RD_SUBITG, returnDoc.RD_CUSTOMERCODE));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return strSql;
    }
    #endregion
}


